import http from "../utils/request.js";

// 错题渲染
export async function renderError() {

    let user_id = localStorage.getItem("userId");
    let { allErrorArr,allCollectionsArr } = await http({ url: "/api/firstpage/getAllError", type: "post", data: { user_id } });

    $("#tab3 .tab2-left").html();
    $("#errorExam").html();
    $(".myError").html(allErrorArr.length);
    //左边题目
    let content = allErrorArr.map(item => {

        let rightKey = Number(item.errorQuestions_id.RightKey);

        let key;
        if (rightKey == 0 ) {
            key = "A"
        } else if (rightKey == 1 ) {
            key = "B"
        }
        else if (rightKey == 2) {
            key = "C"
        } else {
            key = "D"
        }
        let userKey;
        if (item.ErrorAnswer == 0) {
            userKey = "A"
        } else if (item.ErrorAnswer == 1) {
            userKey = "B"
        }
        else if (item.ErrorAnswer == 2) {
            userKey = "C"
        } else {
            userKey = "D"
        }
        return `<div class="examTi" allError=${item.errorQuestions_id._id}>
        <dl>
            <dt>${item.errorQuestions_id.question}</dt>
            <dd><span>A</span><span>${item.errorQuestions_id.answer[0]}</span></dd>
            <dd><span>B</span><span>${item.errorQuestions_id.answer[1]}</span></dd>
            <dd><span>C</span><span>${item.errorQuestions_id.answer[2]}</span></dd>
            <dd><span>D</span><span>${item.errorQuestions_id.answer[3]}</span></dd>
        </dl>
        <div class="buttonbox">
        <button class="collectExam">收藏</button>
        <button class="markExam">标记已学会</button>
        <button class="preExam">上一题</button>
        <button class="nextExam">下一题</button>
    </div>
        <div class="keyanswer">

        <p>
        <span>考生答案:</span>
        <span>${userKey}</span>
        <span class=""></span>
    </p>
    <p>
        <span>正确答案:</span>
        <span class="corG">${key}</span>

    </p>
    <p>
        <span>解析:</span>
        <span class="col9">${item.errorQuestions_id.analysis}</span>

    </p>
        </div>
    </div>`
    })
    $("#tab3 .tab2-left").html(content);


    for(let k=0;k<allErrorArr.length;k++){
        
        for(let n=0;n<allCollectionsArr.length;n++){
            if(allErrorArr[k].errorQuestions_id._id==allCollectionsArr[n].questions_id._id){

               
                $(`[allerror=${allErrorArr[k].errorQuestions_id._id}] .collectExam`).html("已收藏");
                $(`[allerror=${allErrorArr[k].errorQuestions_id._id}] .collectExam`).addClass("del");
            }
        }
        $(`[allError=${allErrorArr[k].errorQuestions_id._id}] dd`).eq(allErrorArr[k].errorQuestions_id.RightKey).addClass("activeYes");
        $(`[allError=${allErrorArr[k].errorQuestions_id._id}] dd`).eq(allErrorArr[k].ErrorAnswer).addClass("activeErr");   
   }
    $('#tab3 .tab2-left .examTi').eq(0).addClass('show');
    let num = 1;
    // //右边选项
    let rightContent = allErrorArr.map(item => {

        return ` <div class="box" data1=${item.errorQuestions_id._id}>
        ${num++}
    </div>`
    })
    $("#errorExam").html(rightContent);
    $("#errorExam .box").eq(0).addClass('active');
};

// 收藏渲染
export async function renderCollections() {

    let user_id = localStorage.getItem("userId");
    let { allCollectionsArr } = await http({ url: "/api/firstpage/getAllCollections", type: "post", data: { user_id } });

    $("#tab2 .tab2-left").html();
    $("#checkCollectExam").html();
    $(".myCollection").html(allCollectionsArr.length);
    //左边题目
    let content = allCollectionsArr.map(item => {

        let rightKey = Number(item.questions_id.RightKey);
        let key;
        if (rightKey == 0) {
            key = "A"
        } else if (rightKey == 1) {
            key = "B"
        }
        else if (rightKey == 2) {
            key = "C"
        } else {
            key = "D"
        }

        return `<div class="examTi" allCollections=${item.questions_id._id}>
        <dl>
            <dt>${item.questions_id.question}</dt>
            <dd><span>A</span><span>${item.questions_id.answer[0]}</span></dd>
            <dd><span>B</span><span>${item.questions_id.answer[1]}</span></dd>
            <dd><span>C</span><span>${item.questions_id.answer[2]}</span></dd>
            <dd><span>D</span><span>${item.questions_id.answer[3]}</span></dd>
        </dl>
        <div class="buttonbox">
            <button class="delExam">取消收藏</button>
            <button class="preExam">上一题</button>
            <button class="nextExam">下一题</button>
        </div>
        <div class="keyanswer">

            <p>
                <span>正确答案:</span>
                <span class="corG">${key}</span>

            </p>
            <p>
                <span>解析:</span>
                <span class="col9">${item.questions_id.analysis}</span>

            </p>
        </div>
    </div>`
    })
    $("#tab2 .tab2-left").html(content);
    for(let k=0;k<allCollectionsArr.length;k++){
        
         $(`[allCollections=${allCollectionsArr[k].questions_id._id}] dd`).eq(allCollectionsArr[k].questions_id.RightKey).addClass("activeYes");
        
        
    }
   
    

    $('#tab2 .tab2-left .examTi').eq(0).addClass('show');
    let num = 1;
    // //右边选项
    let rightContent = allCollectionsArr.map(item => {

        return ` <div class="box" data=${item.questions_id._id}>
        ${num++}
    </div>`
    })
    $("#checkCollectExam").html(rightContent);
    $("#checkCollectExam .box").eq(0).addClass('active');
};

//动态生成5个模块（直接加载）
export async function renderTypes() {

    let { allTypesArr } = await http({ url: "/api/firstpage/getAllTypes", type: "get" });


    $("#testTypesShow").html();
    let content = allTypesArr.map(item => {
        return `<a href="tikuList.html" data=${item._id}>
        <div class="smallBox">
            <span>${item.examType}</span>
            <div class="logo"></div>
        </div>
    </a>`
    })
    $("#testTypesShow").html(content);

};

//渲染题库列表
export async function renderTiKuList() {


    let user_id = localStorage.getItem("userId");

    let TypeId = sessionStorage.getItem("TypeId");
    let checkBox = $("#allTestsFinished").val();


    let { currentCompletedArr, allCompletedTestsArr } = await http({ url: "/api/firstpage/isOkList", type: "post", data: { TypeId, user_id, checkBox } });

    $("main").html();
    let content = currentCompletedArr.map(item => {

        for (let i = 0; i < allCompletedTestsArr.length; i++) {
            if (item._id == allCompletedTestsArr[i].test_id._id) {
                return `<div class="box" data=${item._id}>
                <div class="title">
                    ${item.Title}${item.KnowledgePointId.KnowledgePoint}${item.TypeId.examType}
                </div>
                <div class="title">
                    <span>考试类型：</span><span>${item.TypeId.examType}</span>
                </div>
                <div class="title">
                    <span>考试地址：</span><span>信息中心会议室</span>
                </div>
                <div class="title">
                    <span>已考人数：</span><span>343人</span>
                </div>
                <button class="joinin">已完成考试，点击查看解析</button>

                </div>`
            }
        }
        return `<div class="box" data=${item._id}>
                <div class="title">
                    ${item.Title}${item.KnowledgePointId.KnowledgePoint}${item.TypeId.examType}
                </div>
                <div class="title">
                    <span>考试类型：</span><span>${item.TypeId.examType}</span>
                </div>
                <div class="title">
                    <span>考试地址：</span><span>信息中心会议室</span>
                </div>
                <div class="title">
                    <span>已考人数：</span><span>343人</span>
                </div>
                <button class="join">参加考试</button>
                </div>`

    })
    $("main").html(content);

};

//排行榜渲染
export async function renderRankingTests() {

    let { allTestsArr } = await http({ url: "/api/firstpage/getAllTest", type: "get" });


    $("#allTests").html();
    let content = allTestsArr.map(item => {
        return `<option value=${item._id}>${item.Title}${item.KnowledgePointId.KnowledgePoint}${item.TypeId.examType}</option>`
    })
    $("#allTests").html(content);
}

// 排名
export async function renderUsersRanking() {
    let test_id = $("#allTests option:selected").val();
    if (!test_id) {
        test_id = "610c94879809f147bc108156";
    }
    console.log("test_id", test_id);
    let { userTestsArr } = await http({ url: "/api/firstpage/ranking", type: "post", data: { test_id } });

    userTestsArr.sort((a, b) => {

        return b.score - a.score;
    })


    $("#userRanking").html();
    let userId = localStorage.getItem("userId");
    let firstContent = "未参加考试";
    for (let i = 0; i < userTestsArr.length; i++) {
        if (userTestsArr[i].user_id._id == userId) {
            firstContent = `<div class="paiming">
            <div class="left">
                <p>${i + 1}</p>
                <p>${userTestsArr[i].user_id.userName}</p>
            </div>
            <p>${userTestsArr[i].score}</p>
        </div>`
        }
    }
    $("#userRanking").html(firstContent);
    let num = 1;
    let content = userTestsArr.map(item => {

        return ` <div class="paiming2">
        <div class="left">
            <p>${num++}</p>
            <p>${item.user_id.userName} </p>
        </div>
        <p>${item.score} </p>
    </div>`
    })
    $("#userRanking").append(content);


}


//进入考试题目界面渲染
export async function renderTestQue() {

    let tests_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");


    let { test, user } = await http({ url: "/api/beginExam/getExamUser", type: "post", data: { tests_id, user_id } });
    $("main header h3").html(`${test[0].Title}${test[0].KnowledgePointId.KnowledgePoint}${test[0].TypeId.examType}`);
    $("main .processInfo").html();


    let firstContent = test.map(item => {

        return ` <div class="margright" >
        <dl>
            <dt>试卷信息</dt>
            <dd><span>考试类型:</span><span>${item.TypeId.examType}</span></dd>
            <dd><span>考试时间:</span><span>${item.StayTime}</span></dd>
            <dd><span>答卷时间:</span><span>${item.AnswerTime}分钟</span></dd>
            <dd><span>考试方式:</span><span>线上</span></dd>
        </dl>
    </div> `
    });
    $("main .processInfo").html(firstContent);
    let content = user.map(item => {

        return ` 
      <div class="right">
        <dl>
            <dt>考生信息</dt>
            <dd><span>姓&nbsp;&nbsp;&nbsp;&nbsp;名:</span><span>${item.userName}</span></dd>
            <dd><span>证件号码:</span><span>${item._id}</span></dd>
            <dd><span>部&nbsp;&nbsp;&nbsp;&nbsp;门:</span><span>信息中心</span></dd>
        </dl>
        <a class="error-message">信息有误？去修改</a>
    </div>`
    });

    $("main .processInfo").append(content);


}

export function selectQue(a) {
    if (a == "A") {
        return 0;
    } else if (a == "B") {
        return 1;
    } else if (a == "C") {
        return 2;
    } else {
        return 3;
    }
}
export function selectQueABC(a) {
    if (a == "0") {
        return "A";
    } else if (a == "1") {
        return "B";
    } else if (a == "2") {
        return "C";
    } else {
        return "D";
    }
}
//考试试题渲染
export async function renderTestQuestions() {

    let tests_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");
    let { questions, test } = await http({ url: "/api/beginExam/getExamUser", type: "post", data: { tests_id, user_id } });
    $("#title").html(`${test[0].Title}${test[0].KnowledgePointId.KnowledgePoint}${test[0].TypeId.examType}`);

    $(".answer-card .corR").html(`未答${questions.length}题`);

    $(".inExam-questions .left-questions").html();
    $("#anwer-btns").html();
    $("#testType").html(test[0].TypeId.examType);
    let num = 1;
    let count = 1;
    let n = 1;
    let leftContent1 = questions.map(item => {

        return ` <div class="carousel-item ${item._id}">
        <h3>
          <span>第${num++}题单选题</span>
          <div>第<span>${count++}</span> 题/共<span>${questions.length}</span>题</div>
        </h3>
        <dl class="options">
          <dt>${item.question}</dt>
          <dd><span>A</span><span>${item.answer[0]}</span></dd>
          <dd><span>B</span><span>${item.answer[1]}</span></dd>
          <dd><span>C</span><span>${item.answer[2]}</span></dd>
          <dd><span>D</span><span>${item.answer[3]}</span></dd>
        </dl>

        <div class="begin-test marhT76"> <button class="testBtn">下一题</button></div>
      </div> `
    });
    let rightContent1 = questions.map(item => {
        return `<button class="" id=${item._id}-btn type="button">${n++}</button> `
    });

    $(".inExam-questions .left-questions").html(leftContent1);
    $('.inExam-questions .left-questions .carousel-item').eq(0).addClass('active');
    $("#anwer-btns").html(rightContent1);

    $('#anwer-btns button').eq(0).addClass('inTheAns');

    let quesArr = JSON.parse(sessionStorage.getItem("quesArr"));
    if (quesArr != null) {
        $(".answer-card .corR").html(`未答${questions.length-quesArr.length}题`);
        let divArr = $('.left-questions>div ');
        let idArr = [];
        for (let k = 0; k < divArr.length; k++) {
            idArr[idArr.length] = $('.left-questions>div').eq(k).attr('class').split(' ')[1];
        }

        for (let j = 0; j < idArr.length; j++) {

            let id = idArr[j];
            for (let i = 0; i < quesArr.length; i++) {
                if (quesArr[i]._id == id) {
                    let key = selectQue(quesArr[i].selectVal);
                    $(`.${id} .options dd`).eq(key).attr("class", "activeBlue");
                    $(`#${id}-btn`).attr('data-flag', true)
                    $(`#${id}-btn`).addClass('greenBack');
                    break;
                }
            }
        }

    }

}


//解析渲染
export async function renderTestAnalysis() {

    let test_id = sessionStorage.getItem("testId");
    let user_id = localStorage.getItem("userId");
    let { completedQue, completedTest } = await http({ url: "/api/beginExam/viewResolution", type: "post", data: { test_id, user_id } });
    // console.log(completedQue, completedTest);
    $("#title").html(`${completedQue[0].test_id.Title}${completedQue[0].questions_id.KnowledgePointId.KnowledgePoint}${completedQue[0].test_id.TypeId.examType}`);

    $(".inExam-questions .left-questions").html("");
    $("#anwer-btns").html("");
    $("#testScore").html(completedTest[0].score);
    let cuoTiArr = [];
    let num = 1;
    let count = 1;
    let n = 1;
    let leftContent1 = completedQue.map(item => {
        let userKey = item.user_answer;
        userKey = selectQueABC(userKey);
        let key = item.questions_id.RightKey;
        key = selectQueABC(key);
        return ` <div class="carousel-item ${item.questions_id._id}">
            <h3>
                <span>${num++}</span>
                <div>第<span>${count++}</span> 题/共<span>${completedQue.length}</span>题</div>
            </h3>
            <dl>
                <dt> ${item.questions_id.question}</dt>
                <dd><span>A</span><span>${item.questions_id.answer[0]}</span></dd>
                <dd class=""><span>B</span><span>${item.questions_id.answer[1]}</span></dd>
                <dd class=""><span>C</span><span>${item.questions_id.answer[2]}</span></dd>
                <dd><span>D</span><span>${item.questions_id.answer[3]}</span></dd>
            </dl>
            <div class="keyanswer">
                <p>
                    <span>考生答案:</span>
                    <span>${userKey}</span>
                    <span class="isYes"></span>
                </p>
                <p>
                    <span>正确答案:</span>
                    <span class="corG">${key}</span>

                </p>
                <p>
                    <span>解析:</span>
                    <span class="col9">${item.questions_id.analysis}</span>
                </p>
            </div>
            <div class="begin-test"> <button class="testBtn">下一题</button></div>
                </div> `


    });

    let rightContent1 = completedQue.map(item => {
        return `<button class="" type="button" id="${item.questions_id._id}">
        ${n++}
        <span class=""></span>
    </button> `
    });

    $(".inExam-questions .left-questions").html(leftContent1);
    $('.inExam-questions .left-questions .carousel-item').eq(0).addClass('active');
    $("#anwer-btns").html(rightContent1);

    $('#anwer-btns button').eq(0).addClass('inTheAns');
    for (let k = 0; k < completedQue.length; k++) {
        if (completedQue[k].questions_id.RightKey != completedQue[k].user_answer) {

            cuoTiArr[cuoTiArr.length] = completedQue[k];
           
           $(`.${completedQue[k].questions_id._id} .keyanswer p span`).eq(2).attr("class","isCorrect");
           $(`.${completedQue[k].questions_id._id} dd`).eq(completedQue[k].user_answer).addClass("activeErr");
           $(`.${completedQue[k].questions_id._id} dd`).eq(completedQue[k].questions_id.RightKey).addClass("activeYes");

           $(`#${completedQue[k].questions_id._id} span`).addClass("wrong-icon")

        }else{
            $(`.${completedQue[k].questions_id._id} .keyanswer p span`).eq(2).attr("class","isCorrect isYes");
            $(`.${completedQue[k].questions_id._id} dd`).eq(completedQue[k].questions_id.RightKey).addClass("activeYes");
            $(`#${completedQue[k].questions_id._id} span`).addClass("right-icon")
        }
    }
    $(".answer-card .corR").html(`错误${cuoTiArr.length}题`);


}

//渲染修改界面
export async function renderUserUpdate() {

    let user_id = localStorage.getItem("userId");

    let { user } = await http({ url: "/api/users/data", type: "post",data:{user_id} });


    $("#phone").html(user[0].userPhone);
    $("#firstName").html(user[0].userName);
    
    $("#touXiang").attr("src",`http://127.0.0.1:3000/../images/${user[0].imagePath}`);
    $("#name").val(user[0].userName);
    if(user[0].userGender=="男"){
        $("#man").prop("checked",true);
    }else{
        $("#woman").prop("checked",true);
    }
    
}

export async function renderName(){
    let user_id = localStorage.getItem("userId");
    
    let { user } = await http({ url: "/api/users/data", type: "post",data:{user_id} });
    $("#firstName").html(user[0].userName);
}